var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;

var BlogSchame = new Schema({
    title: String, //文章标题
    content: String, //文章内容
    poster: String, //文章海报地址
    category:{
        type:ObjectId,
        ref:'Category'
    },
    flag: String, //标签
    reads: { //阅读次数
        type: Number,
        default: 0
    },
    author: {
        type: ObjectId,
        ref: 'User'
    },
    meta: {
        createAt: { //创建时间
            type: Date,
            default: Date.now()
        },
        updataAt: { //更新时间
            type: Date,
            default: Date.now()
        }
    }
});

BlogSchame.pre('save', function(next) {
    var blog = this;
    if (blog.isNew) {
        blog.meta.createAt = blog.meta.updataAt = Date.now();
    } else {
        blog.meta.updataAt = Date.now();
    }
    next();
});


BlogSchame.statics = {
    fetch: function(cb) {
        return this
            .find({})
            .sort({
                'meta.createAt': -1
            })
            .exec(cb)
    },
    fetchByAttr: function(value, cb) {
        return this
            .find(value)
            .sort('meta.createAt')
            .exec(cb)
    },
    findOneByAttr: function(value, cb) {
        return this
            .findOne(value)
            .exec(cb)
    },
    top: function(cb) {
        return this
            .find({})
            .skip(1 * (10 - 1), cb)
            .limit(100)
            .sort('meta.createAt')
            .exec(cb)
    }
}

module.exports = BlogSchame;
